OS=$(shell uname -s)
CC=gcc

ifeq ($(OS),Darwin)
	gcc6=/usr/local/Cellar/gcc/6.1.0/bin/gcc-6
	gcc6_exist=$(shell ls -l $(gcc6)|grep -i gcc)
	ifneq ($(strip $(gcc6_exist)),)
		CC=$(gcc6)
  else
		CC=clang
  endif
else
	CC=gcc
endif


libgit2=../build/libgit2
includes=$(libgit2)/include
libs=$(libgit2)/lib

CFLAGS +=-I$(includes) -g
LDFLAGS += -L$(libs)
LIBRARIES += -lgit2

objs=repository commit tree blob create_commit create_ref fetch search_repo walk_tree
objects=$(patsubst %,test_%.o,$(objs))
sources=$(patsubst %,test_%.c,$(objs))

# If the first argument is "run"...
ifeq (run,$(firstword $(MAKECMDGOALS)))
  # use the rest as arguments for "run"
  ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS))
  # ...and turn them into do-nothing targets
  $(eval $(ARGS):;@:)
endif

all:
	@for obj in `echo $(objs)`; \
	do \
		echo "compile test_$$obj.c ..."; \
		$(CC) $(CFLAGS) $(LDFLAGS) $(LIBRARIES) -Wl,-rpath=$(libs) -o test_$$obj.o test_$$obj.c; \
	done \

.PHONY: run
run:
	$(CC) $(CFLAGS) $(LDFLAGS) $(LIBRARIES) -Wl,-rpath=$(libs) -o test_$(ARGS).o test_$(ARGS).c
	./"test_$(ARGS).o"

lib:
	cd ../bundle/libgit2; mkdir build; cd build; cmake .. -DCMAKE_INSTALL_PREFIX=../../../build/libgit2 -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON; make install

clean:
	rm -rf $(objects)

clean_all:
	rm -rf ../build
	rm -rf ../bundle/libgit2/build
	rm -rf $(objects)